<script id="draw-shader-vs" type="x-shader/x-vertex">
precision mediump float;

attribute vec2 inPos;
varying   vec2 vertPos;

void main()
{
    vertPos     = inPos;
    gl_Position = vec4( inPos, 0.0, 1.0 );
}
</script>

<script id="draw-shader-fs" type="x-shader/x-fragment">
precision mediump float;

varying vec2      vertPos;
uniform sampler2D u_texture;
uniform sampler2D u_maskTexture;
uniform vec2      u_vpsize;
uniform vec2      u_mouse;
uniform float     u_maxDistance;
uniform float     u_exponent;
uniform float     u_lightup;

void main()
{
    float aspect       = u_vpsize[0]/u_vpsize[1];
    vec2  distVec      = (vertPos - u_mouse) * vec2(max(1.0,aspect), max(1.0,1.0/aspect));
    float distance     = length(distVec);
    float mixK         = pow( distance / u_maxDistance, u_exponent ); 
    vec2  texCoord     = vertPos * 0.5 + 0.5;
    vec3  texColor     = texture2D( u_texture, texCoord.st ).rgb;
    vec3  grayColor    = vec3( 0.2126 * texColor.r + 0.7152 * texColor.g + 0.0722 * texColor.b );
    vec2  maskTexCoord = 0.5 + 0.5 * distVec / u_maxDistance; 
    float mask         = texture2D( u_maskTexture, maskTexCoord ).a;
    vec3  finalColor   = mix( grayColor, texColor * u_lightup, ( 1.0 - clamp( mixK, 0.0, 1.0 ) ) * mask );
    gl_FragColor       = vec4( finalColor.rgb, 1.0 );
}
</script>

<style>
html,body { margin: 0; overflow: hidden; }
#gui { position : absolute; top : 0; left : 0; font-size : large; }
#ref-link { position : absolute; bottom : 0; left : 0; font-size : large; }  
</style>

<body>

<form id="gui" name="inputs">
<table>
    <tr> <td> <font color= #CCF>max. distance</font> </td> 
            <td> <input type="range" id="maxDist" min="1" max="100" value="33"/></td> </tr>
    <tr> <td> <font color= #CCF>exponent</font> </td> 
            <td> <input type="range" id="exponent" min="1" max="300" value="100"/></td> </tr>
    <tr> <td> <font color= #CCF>light up</font> </td> 
            <td> <input type="range" id="lightup" min="50" max="200" value="150"/></td> </tr>
</table>
</form>

<canvas id="scene-canvas" style="border: none"></canvas>

<a id="ref-link" href="https://stackoverflow.com/questions/45270803/webgl-shader-to-color-the-texture-according-to-mouse-position/45273087#45273087">
<font color= #a0f040>WebGL shader to color the texture according to mouse position</font>  
</a>

</body>

<script type="text/javascript">
(function loadscene() {    

var canvas, gl, prog, bufObj = {}, textureObj, maskTextureObj;
       
function render(deltaMS){

    var maxDist = document.getElementById( "maxDist" ).value / 100;
    var exponent = document.getElementById( "exponent" ).value / 100;
    var lightup = document.getElementById( "lightup" ).value / 100;

    gl.viewport( 0, 0, vp_size[0], vp_size[1] );
    gl.enable( gl.DEPTH_TEST );
    gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
    var texUnit = 0;
    gl.activeTexture( gl.TEXTURE0 + texUnit );
    gl.bindTexture( gl.TEXTURE_2D, textureObj );
    var maskTexUnit = 1;
    gl.activeTexture( gl.TEXTURE0 + maskTexUnit );
    gl.bindTexture( gl.TEXTURE_2D, maskTextureObj );
    ShProg.Use( progDraw );
    var pos = [ 2.0, 2.0 ];
    if (mousePos[0] > 0 && mousePos[1] > 0 )
        pos = [2.0 * mousePos[0] / vp_size[0] - 1.0, 1.0 - 2.0 * mousePos[1] / vp_size[1]];
    ShProg.SetF2( progDraw, "u_vpsize", vp_size );
    ShProg.SetF2( progDraw, "u_mouse", pos );
    ShProg.SetF1( progDraw, "u_maxDistance", maxDist );
    ShProg.SetF1( progDraw, "u_exponent", exponent );
    ShProg.SetF1( progDraw, "u_lightup", lightup );
    ShProg.SetI1( progDraw, "u_texture", texUnit );
    ShProg.SetI1( progDraw, "u_maskTexture", maskTexUnit );
    gl.enableVertexAttribArray( progDraw.inPos );
    gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
    gl.vertexAttribPointer( progDraw.inPos, 2, gl.FLOAT, false, 0, 0 ); 
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
    gl.drawElements( gl.TRIANGLES, bufObj.inx.len, gl.UNSIGNED_SHORT, 0 );
    gl.disableVertexAttribArray( progDraw.pos );

    requestAnimationFrame(render);
}  

function initScene() {

    canvas = document.getElementById( "scene-canvas");
    gl = canvas.getContext( "experimental-webgl" );
    if ( !gl )
      return;

    textureObj = Texture.LoadTexture2D( "https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/supermario.jpg", true );  
    maskTextureObj = Texture.LoadTexture2D( "https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/bat.png", true );  

    
    progDraw = ShProg.Create( 
      [ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER },
        { source : "draw-shader-fs", stage : gl.FRAGMENT_SHADER }
      ] );
    progDraw.inPos = gl.getAttribLocation( progDraw.progObj, "inPos" );
    if ( progDraw.progObj == 0 )
        return;

    var pos = [ -1, -1, 1, -1, 1, 1, -1, 1 ];
    var inx = [ 0, 1, 2, 0, 2, 3 ];
    bufObj.pos = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( pos ), gl.STATIC_DRAW );
    bufObj.inx = gl.createBuffer();
    bufObj.inx.len = inx.length;
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
    gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( inx ), gl.STATIC_DRAW );

    window.onresize = resize;
    resize();
    requestAnimationFrame(render);
}

function resize() {
    //vp_size = [gl.drawingBufferWidth, gl.drawingBufferHeight];
    vp_size = [window.innerWidth, window.innerHeight];
    //vp_size = [256, 256]
    canvas.width = vp_size[0];
    canvas.height = vp_size[1];
}

var mousePos = [-1, -1];
(function() {
    document.onmousemove = handleMouseMove;
    function handleMouseMove(event) {
        var dot, eventDoc, doc, body, pageX, pageY;

        event = event || window.event; // IE-ism

        if (event.pageX == null && event.clientX != null) {
            eventDoc = (event.target && event.target.ownerDocument) || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;

            event.pageX = event.clientX +
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
              (doc && doc.clientLeft || body && body.clientLeft || 0);
            event.pageY = event.clientY +
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
              (doc && doc.clientTop  || body && body.clientTop  || 0 );
        }

        var x = event.pageX - canvas.offsetLeft;
        var y = event.pageY - canvas.offsetTop;
        mousePos = [-1, -1];
        if ( x >= 0 && x < canvas.width && y >= 0 && y < canvas.height ) {
            mousePos = [x, y]; 
        }
    }
})();

var ShProg = {
Create: function (shaderList) {
    var shaderObjs = [];
    for (var i_sh = 0; i_sh < shaderList.length; ++i_sh) {
        var shderObj = this.Compile(shaderList[i_sh].source, shaderList[i_sh].stage);
        if (shderObj) shaderObjs.push(shderObj);
    }
    var prog = {}
    prog.progObj = this.Link(shaderObjs)
    if (prog.progObj) {
        prog.attrInx = {};
        var noOfAttributes = gl.getProgramParameter(prog.progObj, gl.ACTIVE_ATTRIBUTES);
        for (var i_n = 0; i_n < noOfAttributes; ++i_n) {
            var name = gl.getActiveAttrib(prog.progObj, i_n).name;
            prog.attrInx[name] = gl.getAttribLocation(prog.progObj, name);
        }
        prog.uniLoc = {};
        var noOfUniforms = gl.getProgramParameter(prog.progObj, gl.ACTIVE_UNIFORMS);
        for (var i_n = 0; i_n < noOfUniforms; ++i_n) {
            var name = gl.getActiveUniform(prog.progObj, i_n).name;
            prog.uniLoc[name] = gl.getUniformLocation(prog.progObj, name);
        }
    }
    return prog;
},
AttrI: function (prog, name) { return prog.attrInx[name]; },
UniformL: function (prog, name) { return prog.uniLoc[name]; },
Use: function (prog) { gl.useProgram(prog.progObj); },
SetI1: function (prog, name, val) { if (prog.uniLoc[name]) gl.uniform1i(prog.uniLoc[name], val); },
SetF1: function (prog, name, val) { if (prog.uniLoc[name]) gl.uniform1f(prog.uniLoc[name], val); },
SetF2: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform2fv(prog.uniLoc[name], arr); },
SetF3: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform3fv(prog.uniLoc[name], arr); },
SetF4: function (prog, name, arr) { if (prog.uniLoc[name]) gl.uniform4fv(prog.uniLoc[name], arr); },
SetM33: function (prog, name, mat) { if (prog.uniLoc[name]) gl.uniformMatrix3fv(prog.uniLoc[name], false, mat); },
SetM44: function (prog, name, mat) { if (prog.uniLoc[name]) gl.uniformMatrix4fv(prog.uniLoc[name], false, mat); },
Compile: function (source, shaderStage) {
    var shaderScript = document.getElementById(source);
    if (shaderScript)
        source = shaderScript.text;
    var shaderObj = gl.createShader(shaderStage);
    gl.shaderSource(shaderObj, source);
    gl.compileShader(shaderObj);
    var status = gl.getShaderParameter(shaderObj, gl.COMPILE_STATUS);
    if (!status) alert(gl.getShaderInfoLog(shaderObj));
    return status ? shaderObj : null;
},
Link: function (shaderObjs) {
    var prog = gl.createProgram();
    for (var i_sh = 0; i_sh < shaderObjs.length; ++i_sh)
        gl.attachShader(prog, shaderObjs[i_sh]);
    gl.linkProgram(prog);
    status = gl.getProgramParameter(prog, gl.LINK_STATUS);
    if ( !status ) alert(gl.getProgramInfoLog(prog));
    return status ? prog : null;
} };

var Texture = {};
Texture.HandleLoadedTexture2D = function( image, texture, flipY ) {
    gl.activeTexture( gl.TEXTURE0 );
    gl.bindTexture( gl.TEXTURE_2D, texture );
    gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, flipY != undefined && flipY == true );
    gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT );
  	gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT );
    gl.bindTexture( gl.TEXTURE_2D, null );
    return texture;
}
Texture.LoadTexture2D = function( name, flip ) {
    var texture = gl.createTexture();
    texture.image = new Image();
    texture.image.setAttribute('crossorigin', 'anonymous');
    texture.image.onload = function () {
        Texture.HandleLoadedTexture2D( texture.image, texture, flip )
    }
    texture.image.src = name;
    return texture;
}

initScene();

})();
</script>


